package com.topone.controller;

import com.topone.Exception.FanZoneException;
import com.topone.Form.CouponCategoryForm;
import com.topone.dataObject.CouponCategory;
import com.topone.service.CouponCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/15,0015.
 */
@Controller
@RequestMapping("/seller/category")
@Slf4j
public class SellerCategoryController {

    @Autowired
    private CouponCategoryService categoryService;

    @GetMapping("/list")
    public ModelAndView list(Map<String,Object> map){

        List<CouponCategory> categoryList=categoryService.findAll();
        map.put("categoryList",categoryList);
        return new ModelAndView("category/list",map);
    }

    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "categoryId",required = false) Integer categoryId,
                              Map<String,Object> map){


        if(categoryId !=null){
            CouponCategory couponCategory=categoryService.findOne(categoryId);
            map.put("couponCategory",couponCategory);
        }
        return new ModelAndView("category/index",map);
    }

    @PostMapping("/save")
    public ModelAndView save(@Valid CouponCategoryForm
                                         categoryForm,
                             BindingResult bindingResult,
                             Map<String,Object> map){

        if(bindingResult.hasErrors()){
            map.put("msg",bindingResult.getFieldError().getDefaultMessage());
            map.put("url","/fanZone/seller/category/index");
            return new ModelAndView("common/error",map);

        }
        CouponCategory couponCategory=new CouponCategory();
        try {
            if(categoryForm.getCategoryId()!=null){
                couponCategory=categoryService.findOne(categoryForm.getCategoryId());
            }
            BeanUtils.copyProperties(categoryForm,couponCategory);
            categoryService.save(couponCategory);
        }catch (FanZoneException e){
            map.put("msg",e.getMessage());
            map.put("url","/fanZone/seller/category/index");
            return new ModelAndView("common/error",map);
        }
        map.put("url","/fanZone/seller/category/list");
        return new ModelAndView("common/success",map);

    }
}
